<template>
  <el-dialog v-model="dialogVisible" title="项目管理" width="70%">
    <div class="search-bar">
      <el-button type="primary" @click="handleAdd">新增项目</el-button>
    </div>

    <el-table :data="projectList" border v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="所属地区">
        <template #default="scope">
          <span v-for="(dqName, index) in scope.row.prodqName.split(',')">
            {{ scope.row.proshiName }}{{ dqName }}
            <span v-if="index != Object.keys(scope.row.prodqName.split(',')).length - 1">, </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="hth" label="合同号" />
      <el-table-column prop="promyid" label="项目编号" />
      <el-table-column prop="proname" label="项目名称" />
      <el-table-column prop="probz" label="备注" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
        :total="total" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </el-dialog>

  <!-- 添加新增项目弹窗 -->
  <el-dialog v-model="addDialogVisible" :title="formType == 'edit' ? '编辑项目' : '新增项目'" width="50%">
    <el-form :model="projectForm" label-width="100px">
      <el-form-item :label="index == 0 ? '所属地区' : ''" v-for="(_area, index) in areas" :key="index">
        <div class="area-input-container">
          <el-cascader size="default" :options="areaArr" v-model="areas[index]" />
          <div class="button-container">
            <el-button v-if="index === areas.length - 1" @click="addArea" icon="Plus" />
            <el-button v-if="areas.length > 1" @click="() => removeArea(index)" icon="Minus" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="项目编号">
        <el-input  v-model="projectForm.promyid" />
      </el-form-item>
      <el-form-item label="项目名称">
        <el-input v-model="projectForm.proname" :disabled="formType == 'edit'" />
      </el-form-item>
      <el-form-item label="合同号">
        <el-input v-model="projectForm.hth" />
      </el-form-item> 
      <el-form-item label="备注">
        <el-input v-model="projectForm.probz" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProject" :disabled="!isFormValid">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { pcaTextArr } from 'element-china-area-data'
import request from '@/utils/request';
import { useTreeStore } from '@/stores/treeStore';
const props = defineProps({
  modelValue: Boolean
})
const treeStore = useTreeStore();

const emit = defineEmits(['update:modelValue'])

// 数据相关
const projectList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

let formType = 'edit'

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 添加新的响应式变量
const addDialogVisible = ref(false)
const areas = ref([])
const projectForm = reactive({
  procode: '',
  proname: '',
  probz: '',
  promyid: "",
  hth:""
})

const removeArea = (index) => {
  if (areas.value.length > 1) {
    areas.value.splice(index, 1);
  }
}

const addArea = () => {
  areas.value.push([]);
}

// API调用 - 获取项目列表
const fetchProjects = async () => {
  loading.value = true
  try {
    const { data } = await request.post(`/zhsj/api/getprobysdq?pageindex=${currentPage.value - 1}`)
    projectList.value = data.records
    total.value = data.total
  } catch (error) {
    console.log(error)
    ElMessage.error('加载项目列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProjects()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProjects()
}


// 编辑项目
const handleEdit = (row) => {
  formType = 'edit';
  console.log(row);
  areas.value = row.prodqName.split(',').map((dq) => {
    return ["辽宁省", row.proshiName, dq];
  });

  projectForm.probz = row.probz;
  projectForm.proname = row.proname;
  projectForm.proid = row.proidstr
  projectForm.promyid = row.promyid
  projectForm.hth = row.hth
  addDialogVisible.value = true;
};

// 删除项目
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该项目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await request.post(`/zhsj/api/delpro?proid=${row.id}`)
      ElMessage.success('删除成功')
      fetchProjects() // 重新加载数据
      treeStore.loadTreeData();
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 新增项目
const handleAdd = () => {
  formType = 'add'
  areas.value = [[]]
  projectForm.probz = "";
  projectForm.proname = "";
  projectForm.proid =""; 
  projectForm.promyid = "";
  projectForm.hth= "";
  addDialogVisible.value = true
}


// 添加提交方法
const submitProject = async () => {
  try {
    areas.value.map((area) => console.log(area))
    let from = {
      "proname": projectForm.proname,
      "probz": projectForm.probz,
      "prodq": areas.value.map((area) => area[2]).toString(),
      "proshi": areas.value[0][1],
      "promyid": projectForm.promyid,
      "hth":projectForm.hth
    }
    if(from.prodq.length == 0){
      ElMessage.error('请选择所属地区')
      return
    }
    const url = formType == 'edit' ? '/zhsj/api/savepro' : '/zhsj/api/createpro'
    if (formType == 'edit') {
      from['proid'] = projectForm.proid

    }


    const resp = await request.post(url, from)
    if(resp.code !=20000){
        ElMessage.error(resp.msg)
        return;
    }
    ElMessage.success('添加成功')
    addDialogVisible.value = false
    fetchProjects() // 重新加载数据

    treeStore.loadTreeData();
    
  } catch (error) {
    // ElMessage.error(error.response.data.msg)
  }
}

// 监听对话框显示
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    fetchProjects()
  }
})
let areaArr = computed(() => {
  return pcaTextArr.filter(function (item) {
    return item.label == "辽宁省"
  })
  //  return num1.value + num2.value 
})

const isFormValid = computed(() => {
  return projectForm.proname.trim() !== ''
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.area-input-container {
  display: flex;
  align-items: center;
}

.button-container {
  display: flex;
  margin-left: 10px;
}
</style>